#include "usart.h"
#include "delay.h"
#include "os.h"

UART_HandleTypeDef huart1;


// 在usart.c中添加
#include <stdio.h>

// 重定向printf
int __io_putchar(int ch)
{
    HAL_UART_Transmit(&huart1, (uint8_t*)&ch, 1, HAL_MAX_DELAY);
    return ch;
}

// 重定向getchar
int __io_getchar(void)
{
    uint8_t ch;
    HAL_UART_Receive(&huart1, &ch, 1, HAL_MAX_DELAY);
    return ch;
}

// 串口初始化
void MX_USART1_UART_Init(void)
{
    huart1.Instance = USART1;
    huart1.Init.BaudRate = 115200;
    huart1.Init.WordLength = UART_WORDLENGTH_8B;
    huart1.Init.StopBits = UART_STOPBITS_1;
    huart1.Init.Parity = UART_PARITY_NONE;
    huart1.Init.Mode = UART_MODE_TX_RX;
    huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    huart1.Init.OverSampling = UART_OVERSAMPLING_16;
    
    if (HAL_UART_Init(&huart1) != HAL_OK)
    {
        Error_Handler();
    }
}

// HAL库的MSP初始化回调
void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle)
{
    GPIO_InitTypeDef GPIO_InitStruct = {0};
    
    if(uartHandle->Instance == USART1)
    {
        __HAL_RCC_USART1_CLK_ENABLE();
        __HAL_RCC_GPIOA_CLK_ENABLE();
        
        // PA9-TX, PA10-RX
        GPIO_InitStruct.Pin = GPIO_PIN_9 | GPIO_PIN_10;
        GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
        GPIO_InitStruct.Pull = GPIO_PULLUP;
        GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
        GPIO_InitStruct.Alternate = GPIO_AF7_USART1;
        HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
    }
}

// 阻塞式发送字符串
void uart_send_string(const char *str)
{
    HAL_UART_Transmit(&huart1, (uint8_t*)str, strlen(str), HAL_MAX_DELAY);
}

// 格式化输出（类似printf）
void uart_printf(const char *fmt, ...)
{
    char buf[128];
    va_list args;
    va_start(args, fmt);
    int len = vsnprintf(buf, sizeof(buf), fmt, args);
    va_end(args);
    
    if(len > 0)
    {
        HAL_UART_Transmit(&huart1, (uint8_t*)buf, len, HAL_MAX_DELAY);
    }
}

// 接收一个字节（阻塞式）
uint8_t uart_receive_byte(void)
{
    uint8_t data;
    HAL_UART_Receive(&huart1, &data, 1, HAL_MAX_DELAY);
    return data;
}

// 接收字符串直到回车（阻塞式）
void uart_receive_line(char *buffer, uint16_t max_len)
{
    uint16_t index = 0;
    uint8_t ch;
    
    while(1)
    {
        ch = uart_receive_byte();
        
        // 回显字符
        HAL_UART_Transmit(&huart1, &ch, 1, HAL_MAX_DELAY);
        
        // 回车结束
        if(ch == '\r')
        {
            buffer[index] = '\0';
            HAL_UART_Transmit(&huart1, (uint8_t*)"\r\n", 2, HAL_MAX_DELAY);
            return;
        }
        
        // 退格处理
        if(ch == '\b' && index > 0)
        {
            index--;
            HAL_UART_Transmit(&huart1, (uint8_t*)" \b", 2, HAL_MAX_DELAY);
            continue;
        }
        
        // 普通字符
        if(index < max_len - 1 && ch >= 32 && ch <= 126)
        {
            buffer[index++] = ch;
        }
    }
} 




